'use strict';
const db = uniCloud.database()

exports.main = async (event, context) => {
	const {
		loginName,
		password,
		phone,
		type
	} = event

	// 构造安全的匹配对象
	const matchObj = {}
	if (type === 'account') {
		if (loginName) matchObj.loginName = loginName.trim()
		if (password) matchObj.password = password
	} else {
		if (phone) matchObj.phone = phone.trim()
	}

	// 如果条件为空，直接判失败，避免 match({})
	if (Object.keys(matchObj).length === 0) {
		return {
			code: 1,
			msg: '参数不完整'
		}
	}

	const res = await db.collection('user')
		.aggregate()
		.match(matchObj)
		.limit(1)
		.end()

	const hit = Array.isArray(res.data) && res.data.length > 0
	return hit ?
		{
			code: 0,
			msg: '获取成功',
			data: res.data[0]
		} :
		{
			code: 1,
			msg: type === 'account' ? '获取用户信息失败，请检查用户名或密码' : '验证码或手机号码错误'
		}
}